package eu.telecombretagne.rsm.base.entity;

import java.io.*;
import java.net.*;

import eu.telecombretagne.rsm.base.event.*;
import eu.telecombretagne.rsm.gui.frames.DesktopFrame;
import eu.telecombretagne.rsm.network.utils.ServerManager;

public class NetworkWriterEntity extends Entity {
	
	private Socket socket;
	private ObjectOutputStream oos;
	
	public NetworkWriterEntity (EventChannel ec, String who, Class <?> produced[], Class <?> consumed[]) {
		super (ec, produced, consumed);
		try {
			socket = new Socket ("localhost", ServerManager.getNetworkPort());
			oos = new ObjectOutputStream (socket.getOutputStream ());
			oos.writeObject(who);
		} catch (SocketException se) {
			DesktopFrame.writeLogError(this.getClass().getSimpleName() + ": Socket Exception");
			System.exit(0);
		} catch (IOException ioe) {
			DesktopFrame.writeLogError(this.getClass().getSimpleName() + ": IO Exception");
			System.exit(0);
		}
 	}	
	
	public void run(){
		while (runSwitch) {
			try {
				Event e = this.consume ();
				oos.writeObject (e);
			} catch (InterruptedException ie) {
				DesktopFrame.writeLogError(this.getClass().getSimpleName() + ": " + ie);
				System.exit(0);
			} catch (IOException ioe) {
				DesktopFrame.writeLogError(this.getClass().getSimpleName() + ": " + ioe);
				System.exit(0);
			}
		}
	}
}